package com.easy.auth.controller;

import com.easy.common.bean.SysPermission;
import com.easy.common.bean.SysRole;
import com.easy.common.bean.SysUser;
import com.easy.common.exception.ParameterException;
import com.easy.common.service.IRedisService;
import com.easy.common.service.IUserService;
import com.easy.common.util.JWTUtil;
import com.easy.common.util.PasswordDecode;
import com.easy.common.util.ResultData;
import com.easy.common.util.SYSUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.util.Arrays;

@RestController
@RequestMapping("auth")
@CrossOrigin
public class AuthController {
    @DubboReference
    IUserService userService;
    @DubboReference
    IRedisService redisService;
    @PostMapping("/login")
    public ResultData login(@RequestBody SysUser user){
        //获取用户名和密码
        String username=user.getUsername();
        String password=user.getPassword();
        if (SYSUtil.checkNotEmpty(username,password)){
            //通过用户名获取用户数据
            //需要访问User模块中的服务
            SysUser sysuser=userService.getByUsername(username);
            if (SYSUtil.checkNotNull(sysuser)){
                //比较密码
                String password_data=sysuser.getPassword();//数据中加密的内容
                if (PasswordDecode.decode(password,password_data)){
                    //如果成功就签发token
                    String token=JWTUtil.generateToken(null);
                    String allPermission=getAllPermission(sysuser);
                    System.out.println(allPermission);
                    redisService.set(token,allPermission);
                    return ResultData.success(token);
                }else {
                    throw  new RuntimeException("密码不正确");
                }
            }else{
                throw  new RuntimeException("没有此账号");
            }
        }else {
            throw new ParameterException("参数异常");
        }
        //验证参数
        //通过用户名获取用户数据
        //验证密码是否正确
        //返回对应结果
    }
    private String getAllPermission(SysUser user){
        StringBuilder strb=new StringBuilder();
        for (SysRole role:user.getRoles()){
            strb.append(role.getRolekey());
            strb.append(",");
            for (SysPermission permission:role.getPermissions()){
                strb.append(permission.getPermkey());
                strb.append(",");
            }

        }
        return strb.toString();
    }
}
